import Component from './Component';
import { ITodoData } from '../../../typings';

export interface IListOptions {
  wrapperEl: HTMLElement;
  todoData: ITodoData[];
}

class List extends Component {
  private _wrapperEl: HTMLElement;
  //静态属性
  private static todoData: ITodoData[];

  constructor(options: IListOptions) {
    super();

    this._wrapperEl = options.wrapperEl;
    List.todoData = options.todoData;
  }

  /**
   * 新增一项item至列表中
   * @param val 输入框字符串内容
   */
  public static addItem(val: string) {
    const oTodoList: HTMLElement = document.querySelector('.todo-list');

    //拼接一项item
    const _item: ITodoData = {
      id: new Date().getTime(),
      content: val,
      completed: false
    };

    //给组件内容容器新增_item内容
    List.todoData.push(_item);

    if (List.todoData.length === 1) {
      oTodoList.innerHTML = '';
    }

    //重写<div class="todo-list"></div> 里面的内容 新增一项
    oTodoList.innerHTML += Component.todoView(_item);
  }

  private _handleListClick(e: MouseEvent) {
    const tar = e.target as HTMLElement;
    const tagName = tar.tagName.toLowerCase();

    //拿到todo-list底下所有元素节点
    const oTodoItems: HTMLCollection =
      document.getElementsByClassName('todo-item');

    if (tagName === 'input' || tagName === 'button') {
      //从节点的自定义属性里获取id
      const id: number = parseInt(tar.dataset.id);

      switch (tagName) {
        case 'input':
          this._handleCheckBoxClick(id, oTodoItems);
          break;
        case 'button':
          this._handleBtnClick(id, oTodoItems);
          break;
        default:
          break;
      }
    }
  }

  /**
   * 点击复选框按钮更改状态
   * @param id 为id属性的某一项
   * @param oTodoItems 所有todo-item 节点
   */
  private _handleCheckBoxClick(id: number, oTodoItems: HTMLCollection) {
    //遍历List组件本身的todoData容器
    List.todoData = List.todoData.map((todo: ITodoData, index: number) => {
      if (todo.id === id) {
        //更改completed状态
        todo.completed = !todo.completed;
        //当前那一项 更改completed的样式
        oTodoItems[index].querySelector('span').style.textDecoration =
          todo.completed ? 'line-through' : '';
      }
      //返回修改后的todo
      return todo;
    });
  }

  /**
   * 点击删除按钮删除该项
   * @param id 为id属性的某一项
   * @param oTodoItems 所有todo-item 节点
   */
  private _handleBtnClick(id: number, oTodoItems: HTMLCollection) {
    List.todoData = List.todoData.filter((todo: ITodoData, index: number) => {
      //过滤不符合条件 得到其他所有
      if (todo.id !== id) {
        return todo;
      } else {
        //符合条件时清除该项
        oTodoItems[index].remove();
      }
    });
  }

  public bindEvent() {
    //获取节点<div class="todo-list"></div>
    const oTodoList: HTMLElement = document.querySelector('.todo-list');

    oTodoList.addEventListener(
      'click',
      this._handleListClick.bind(this),
      false
    );
  }

  public render() {
    this._wrapperEl.innerHTML += Component.listView(List.todoData);
  }
}

export default List;
